<?php

/*
 * Hlavní synchronizační funkce - vybere z databáze jeden nebo všechny účty a nechá je postupně synchronizovat
 * $idacc = číslo účtu, který se ma synchronizovat jednoltlivě
 * @vrací true nebo false podle toho, jak skončila synchronizace
 */
function mailcontent_synchro($idacc = '') {
    if ($idacc != "") {
        $accounts = db_query("SELECT * FROM {mailcontent_login} WHERE idacc='".$idacc."'");
        if ($accounts) {
            while ($row = db_fetch_array($accounts)) {
                mailcontent_synchronize_mailbox($row['idacc']);
            }
            drupal_goto('mailcontent/settings');
        }
    } else {
        $accounts = db_query("SELECT * FROM {mailcontent_login}");
        if ($accounts) {
            while ($row = db_fetch_array($accounts)) {
                mailcontent_synchronize_mailbox($row['idacc']);
            }
        }
        drupal_goto('mailcontent/content');
    }
} //OK

/*
 * Funkce, která synchronizuje jeden daný mail - načte zprávy a postupně je validuje a zpracovává za pomoci dalších funkcí
 * $idacc = číslo účtu, který se ma synchronizovat jednoltlivě
 * @vrací true nebo false podle toho, jak skončila synchronizace
 */
function mailcontent_synchronize_mailbox($idacc = '') {
    global $user;

    $delete = mailcontent_get_perm_del();

    $result = db_query("SELECT * FROM {mailcontent_login} WHERE idacc=".$idacc);
    if ($result) {
        while($row = db_fetch_array($result)) {
            $pass = $row['pass'];
            $username = $row['username'];
            if ($row['server'] == '') {
                $res1 = db_query("SELECT * FROM {mailcontent_servis} WHERE name='defaultserver'");
                if ($res1) {
                    $r1 = db_fetch_array($res1);
                    $mailserver = '{'.$r1['value'].'}';
                } else {
                    mailcontent_error(t("Can not find default server adress"));
                }
            } else {
                $mailserver = '{'.$row['server'].'}';
            }

            if (mailcontent_is_timeout_ok($idacc)) {
                $connection = imap_open($mailserver, $username, $pass);
                if ($connection) {
                    db_query("UPDATE {mailcontent_login} SET lastsynchro='".date('Y-m-d H:i:s', strtotime('now'))."' WHERE duid=".$user->uid." and idacc=".$idacc);
                    $num_of_msg = imap_num_msg($connection);
                    $i = 1;
                    while ($i <= $num_of_msg) {
                        $message = imap_headerinfo($connection, $i);
                        if (mailcontent_is_new_message($message->udate, $idacc)) {
                            $actions = mailcontent_is_message_valid(mailcontent_czech_string($message->subject));
                            $from = $message->from;
                            foreach ($from as $id => $object) {
                                $fromaddress = $object->mailbox."@".$object->host;
                            }
                            if ($actions) {
                                if (mailcontent_is_mail_valid($fromaddress, $idacc, $actions)) {
                                    $data['body'] = mailcontent_czech_string($message->subject);
                                    $data['type_content'] = $actions[0];
                                    $data['from_address'] = $fromaddress;
                                    $data['received'] = date(DATE_ATOM, $message->udate);
                                    $data['dateexp'] = '';
                                    $data['datestart'] = '';
                                    $data['copy'] = '';
                                    $data['to_address'] = '';
                                    $data['synchronization'] = '';
                                    $data['duid'] = '';
                                    $data['username'] = '';
                                    $data['state'] = '';
                                    $data['idn'] = '';
                                    if (isset($message->cc)) {
                                        $cc = $message->cc;
                                        foreach ($cc as $id => $object) {
                                            $data['copy'] = $data['copy'].$object->mailbox."@".$object->host."; ";
                                        }
                                        $data['copy'] = substr($data['copy'], 0, strlen($data['copy'])-2);
                                    }
                                    if (isset($message->to)) {
                                        $to = $message->to;
                                        foreach ($to as $id => $object) {
                                            $data['to_address'] = $data['to_address'].$object->mailbox."@".$object->host."; ";
                                        }
                                        $data['to_address'] = substr($data['to_address'], 0, strlen($data['to_address'])-2);
                                    }
                                  $body = '';

                                    foreach ($actions as $val) {
                                        if ($val == 'html') {
                                            $body = mailcontent_czech_string(imap_fetchbody($connection, $i, 2), 1);
                                        }
                                    }

                                    if ($body == '') {
                                        $body = mailcontent_czech_string(imap_fetchbody($connection, $i, 1), 0);
                                    }

                                    if ($body != '') {
                                        $data['body'] = $data['body']."<br>".$body;
                                        $idm = mailcontent_db_add_mail($data);
                                        if ($idm) {
                                        if (mailcontent_parse_body($body, $actions[0], $idm)) {
                                            foreach ($actions as $act) {
                                                switch ($act){
                                                    case "publish":
                                                        mailcontent_publish($idm);
                                                        break;
                                                
                                                    default:
                                                        break;
                                                }
                                            }
                                            if ($delete){
                                                imap_delete($connection, $i);
                                            }
                                            mailcontent_info(t("Message (#".$idm.") was succefully saved into system."));
                                            mailcontent_send_info(t("Message with subject '".mailcontent_czech_string($message->subject)."' from '".$fromaddress."' was accepted!"), $fromaddress);
                                            db_query("UPDATE {mailcontent_login} SET lastmail='".$data['received']."' WHERE idacc=".$idacc);
                                        } else {
                                            db_query("DELETE FROM {mailcontent_mail} WHERE idm=".$idm);
                                            mailcontent_error_parse(t("Message (#".$idm.") can not be saved - error in parsing body of message.."));
                                            mailcontent_send_info(t("Message with subject '".mailcontent_czech_string($message->subject)."' from '".$fromaddress."' was rejected! - Reason: Error in body"), $fromaddress);
                                        }
//                                        $state = mailcontent_message_parse($idm, $body);
                                        //                                      if ($state) {
// update stavu zpravy v DB
                                        //                                        mailcontent_message_state_update($state, $idm);
                                        //                                  }
                                        } else {
                                            mailcontent_error(t('Synchronization of mailbox'." - <b>".$username."</b> ".t("unsuccessfull!")));
                                            imap_close($connection);
                                            db_query("UPDATE {mailcontent_login} SET lastsynchro='".date('Y-m-d H:i:s', strtotime('now'))."' WHERE duid=".$user->uid." and idacc=".$idacc);
                                            return false;
                                        }
                                    } else {
                                        mailcontent_error_parse(t("Message have not body - can not be saved.."));
                                        mailcontent_send_info(t("Message with subject '".mailcontent_czech_string($message->subject)."' from '".$fromaddress."' was rejected! - Reason: Missing body"), $fromaddress);
                                    }


                                    /*                if ($message_id){
                                mailcontent_db_login_upd_date($username, $message->udate);
                                mailcontent_publish_mail($message_id);
                            }
                                    */
                                } else {
                                    mailcontent_error_parse(t("Message with subject '".mailcontent_czech_string($message->subject)."' from '".$fromaddress."' was rejected!"));
                                    mailcontent_send_info(t("Message with subject '".mailcontent_czech_string($message->subject)."' from '".$fromaddress."' was rejected! - Reason: Fault in subject or mailaddress"), $fromaddress);
                                }
                            } else {
                                mailcontent_info(t("Message with subject '".mailcontent_czech_string($message->subject)."' from '".$fromaddress."' is not for drupal module"));
                            }
                        }
                        //               mailcontent_makr_as_read();
                        $i++;
                    }
                    mailcontent_info(t('Synchronization succesfully completed..'));
                    imap_close($connection, CL_EXPUNGE);
                    db_query("UPDATE {mailcontent_login} SET lastsynchro='".date('Y-m-d H:i:s', strtotime('now'))."' WHERE duid=".$user->uid." and idacc=".$idacc);
                    return TRUE;
                } else {
                    mailcontent_error(t("Can not connect to account<b>")." ".$username."</b>", "warning");
                    db_query("UPDATE {mailcontent_login} SET lastsynchro='".date('Y-m-d H:i:s', strtotime('now'))."' WHERE duid=".$user->uid." and idacc=".$idacc);
                    return FALSE;
                }
            } else {
                mailcontent_error(t("Connection is not allowed(for account - <b>").$username.t("</b>)at this time, you must wait.."), "warning");
                return FALSE;
            }

        }
    }
    else {
        drupal_set_message(t("Can not find password for<b>")." ".$username."</b>", "warning");
        return FALSE;
    }
    return FALSE;
} //OK

/*
 * Funkce publikuje přijatý mail
 * $idm - mail k publikaci
 * @vrací číslo mailu, který se uložil do databáze
 */
function mailcontent_publish($idm = 0) {
    global $user;
    if (user_access('content edit')) {
    if (db_result(db_query("SELECT * FROM {mailcontent_mail} WHERE idm=".$idm))) {
        $result = db_query("SELECT * FROM {mailcontent_mail} WHERE idm=".$idm);
        $row = db_fetch_array($result);
        $data['received'] = $row['received'];
        $type = $row['type_content'];
        if(db_result(db_query("SELECT * FROM {mailcontent_content} WHERE idm=".$idm))) {
            $res = db_query("SELECT * FROM {mailcontent_content} WHERE idm=".$idm);
            $i = 0;
            $b = 0;
            while($rw = db_fetch_array($res)) {
                switch ($rw['type_content']) {
                    case "title":
                        $data['title'] = $rw['value_content'];
                        break;
                    case "teaser":
                        $data['teaser'] = $rw['value_content'];
                        break;
                    case "body":
                        $data['body'] = $rw['value_content'];
                        break;
                    case "author":
                        $author = $rw['value_content'];
                        break;
                    case "type_art":
                        $data['type_art'] = $rw['value_content'];
                        break;
                    case "start_time":
                        $start_time = $rw['value_content'];
                        break;
                    case "end_time":
                        $end_time = $rw['value_content'];
                        break;
                    case "inquiry_question":
                        $inquiry[$i] = $rw['value_content'];
                        $i++;
                        break;
                    case "block":
                        $block[$b] = $rw['value_content'];
                        $b++;
                        break;
                    default:
                        break;
                }
            }

            switch ($type) {
                case "task":
                    $data['body'] = $data['body']."<br><br>".t("Task expires: ").$end_time;
                    break;
                case "schedule":
                    $data['body'] = $data['body']."<br><br>".t("Schedule start: ").$start_time;
                    $data['body'] = $data['body']."<br>".t("Schedule expires: ").$end_time;
                    break;
                case "inquiry":
                    if ($inquiry) {
                        $data['body'] = $data['body']."<br><br>".t("Assigned questions: ");
                        foreach ($inquiry as $value) {
                            $data['body'] = $data['body']."<br>".$value;
                        }
                    }
                    break;
                default:
                    break;
            }

            if ($author){
                $data['body'] = $data['body']."<br><br>".t("Author: ").$author;
            }

            if ($block) {
                foreach ($block as $value) {
                    $data['body'] = $data['body']."<br>".$value;
                }
            }
        }
        $idn = mailcontent_db_add_node($data);
        if ($idn) {
            if (mailcontent_db_update_mail_status($idm, $idn)) {
                mailcontent_info(t("Mail was published.."));
                return true;
            } else {
                mailcontent_error(t("Mail was saved as article, but can not be updated in content table, please contact admin!"));
                return false;
            }
        } else {
            mailcontent_error(t("Mail (#".$idm.") can not be published!"));
            return false;
        }
    } else {
        mailcontent_error(t("Article from mail #".$idm." can not be published.."));
        return false;
    }
    } else {
        mailcontent_error_permissions("User ".$user->uid." has not permission");
    }
} //OK



?>
